<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
	<base href="/">
	<meta charset="utf-8">
	<link rel="stylesheet" href="fonts/iconfont.css">
	<link rel="stylesheet" href="cart/cart.css">
	<title>TCL 商城购物车</title>
</head>

<body>
<!-- 头部导航 -->
<header class="top-bar tonglan">
	<div class="top-nav-wrapper w">
		<!-- 导航条左边 -->
		<div class="top-nav-left">

		</div>
		<!-- 导航条右边 -->
		<div class="top-nav-right">

			<ul>
				<li><a href="page/index">首页</a></li><span></span>
				<li><a href="page/orderConfirm">我的订单</a></li> <span></span>
				<li><a href="page/cart">购物车</a></li> <span></span>
				<li class="lists-title"><a href="page/profile">个人中心</a></li><span></span>
				<li>
					<a href="#" id="logoutLink">退出登录</a>
				</li>
			</ul>
		</div>
	</div>
</header>

<!-- 主要内容：购物车表格 -->
<main>
	<table class="cart w">
		<thead>
		<tr>
			<th>
				<input type="checkbox" id="checkall" class="check-all">
				<label for="checkall">
					<i class="iconfont icon-checkbox"></i> 全选
				</label>
			</th>
			<th>商品信息</th>
			<th>单价</th>
			<th>数量</th>
			<th>小计</th>
			<th>操作</th>
		</tr>
		</thead>
		<tbody id="cart-items">
		<thead>

		</thead>
		</tbody>
		<tfoot>
		<tr>
			<td colspan="7">
				<div class="amout-wrapper">已结算<span class="amout"></span> 个</div>
				<div class="total-wrapper">总金额: <span class="total"></span> 元</div>
				<button class="btn-settle btn-settle-checkout">去结算</button>
			</td>
		</tr>
		</tfoot>
	</table>
</main>

<!--<script src="cart/cart.js"></script>-->
<script src="layui/layui.all.js"></script>
<script type="text/html" id="cart-item-template">
	<tr>
		<td>
			<input type="checkbox" cartname="cartcheck" class="item-check" cartproductid="{{productid}}">
			<label>
				<i class="iconfont icon-checkbox"></i>
			</label>
		</td>
		<td><img src="" alt="商品图片" easyname="cartimg" width="50"></td>
		<td class="price" cartname="cartprice">0.00</td>
		<td class="quantity">  <!-- 删除 text(data[i].quantity) 的注入点 -->
			<button cartname="subtractbtn" cartproductid="{{productid}}">-</button>
			<input type="text" name="number" value="{{quantity}}" cartname="cartnumber" cartproductid="{{productid}}">
			<button cartname="plusbtn" cartproductid="{{productid}}">+</button>
		</td>
		<td class="subtotal" cartname="carttotal">0.00</td>
		<td><button type="button" cartname="cartdelete" productid="" class="cart-delete-btn">删除</button></td>
	</tr>
</script>
<script>
	const $ = layui.$;
	const layer = layui.layer;
	showCarts();

	// 加载购物车数据
	function showCarts() {
		$.ajax({
			url: 'cart/getCarts',
			success: function (result) {
				const data = result.data;
				const itemTemplate = $('#cart-item-template').html();
				$('#cart-items').empty();

				data.forEach(item => {
					const compiledTemplate = itemTemplate
							.replace(/{{productid}}/g, item.productid)
							.replace(/{{quantity}}/g, item.quantity);

					const $item = $(compiledTemplate);
					// 检查 item.product 是否存在
					if (item.product && item.product.imgurl) {
						console.log('设置的图片路径:', item.product.imgurl);
						$item.find("img").attr("src", item.product.imgurl);
					} else {
						console.log('使用默认图片');
						// 设置默认图片地址
						$item.find("img").attr("src", "default_image.jpg");
					}
					if (item.product) {
						$item.find(".price").text(item.product.price.toFixed(2));
						$item.find(".subtotal").text((item.product.price * item.quantity).toFixed(2));
					}
					$item.find("[cartname='cartdelete']").attr("cartproductid", item.productid);
					$('#cart-items').append($item);
				});

				checkAllTotal(); // 初始化统计
			}
		});
	}

	// 删除商品
	$('#cart-items').on('click', '[cartname="cartdelete"]', function () {
		const productid = $(this).attr("cartproductid");
		const $tr = $(this).closest('tr');

		layer.confirm("确认删除商品吗？", {
			icon: 3,
			title: '提示'
		}, function (index) { // 这里index是弹窗实例索引
			// 立即关闭确认对话框
			layer.close(index);

			$.ajax({
				url: "cart/delete",
				data: { productid },
				success: function (result) {
					showCarts();
					checkAllTotal();
					if (result.code === 200) {
						// 先更新界面
						$tr.remove();
						layer.msg(result.msg, { icon: 1 });
					} else {
						layer.msg(result.msg || "删除失败", { icon: 1 });
					}
				},
				error: function () {
					layer.msg("请求失败，请检查网络", { icon: 2 });
				}
			});
		});
	});
	// 数量增减
	$(document).on('click', '[cartname="subtractbtn"]', function () {
		const $input = $(this).siblings('[name="number"]');
		let current = parseInt($input.val()) || 1;
		if (current > 1) changeNumber($input, $(this).attr('cartproductid'), current - 1);
	});

	$(document).on('click', '[cartname="plusbtn"]', function () {
		const $input = $(this).siblings('[name="number"]');
		let current = parseInt($input.val()) || 1;
		if (current < 99) changeNumber($input, $(this).attr('cartproductid'), current + 1);
	});

	// 输入框修改数量
	$('#cart-items').on('blur', '[name="number"]', function () {
		let newVal = Math.min(99, Math.max(1, $(this).val()));
		$(this).val(newVal);
		changeNumber($(this), $(this).attr('cartproductid'), newVal);
	});

	// 全选功能
	$('#checkall').change(function () {
		$('[cartname="cartcheck"]').prop('checked', this.checked);
		checkAllTotal();
	});

	// 勾选商品时更新统计
	$('#cart-items').on('change', '[cartname="cartcheck"]', checkAllTotal);

	// 修改数量请求
	function changeNumber($input, productid, number) {
		number = Math.max(1, Math.min(99, number));
		const oldVal = parseInt($input.val()) || 1;

		$.ajax({
			url: 'cart/edit',
			method: 'POST',
			data: { productid, number, _: new Date().getTime() },
			success: function (result) {
				showCarts();
				checkAllTotal();
				if (result.code === 200) {
					$input.val(number);
					const $row = $input.closest('tr');
					const price = parseFloat($row.find('.price').text());
					const subtotal = price * number;
					$row.find('.subtotal').text(subtotal.toFixed(2));
					checkAllTotal();
				} else {
					layer.msg(result.msg, { icon: 1 });
					$input.val(oldVal);
				}
			},
			error: function () {
				$input.val(oldVal);
				layer.msg('网络错误，请重试', { icon: 2 });
			}
		});
	}

	// 计算总金额
	function checkAllTotal() {
		let total = 0, checkedItems = 0;
		$('[cartname="cartcheck"]:checked').each(function () {
			const subtotal = parseFloat($(this).closest('tr').find('.subtotal').text());
			total += subtotal;
			checkedItems++;
		});
		$('.total').text(total.toFixed(2));
		$('.amout').text(checkedItems);
	}

	// 为去结算按钮添加点击事件
	$('.btn-settle-checkout').on('click', function () {
		const selectedProducts = [];
		$('[cartname="cartcheck"]:checked').each(function () {
			const productId = $(this).attr('cartproductid');
			const quantity = parseInt($(this).closest('tr').find('[name="number"]').val());
			selectedProducts.push({ productid: productId, quantity: quantity });
		});

		if (selectedProducts.length === 0) {
			layer.msg('请选择要结算的商品', { icon: 2 });
			return;
		}

		const productsParam = encodeURIComponent(JSON.stringify(selectedProducts));
		const orderUrl = `page/order?products=${productsParam}`;
		window.location.href = orderUrl;
	});

	// 为去结算按钮添加点击事件
	$('.btn-settle-checkout').on('click', function () {
		const selectedProductIds = [];
		const selectedCounts = [];
		$('[cartname="cartcheck"]:checked').each(function () {
			const productId = $(this).attr('cartproductid');
			const quantity = parseInt($(this).closest('tr').find('[name="number"]').val());
			selectedProductIds.push(productId);
			selectedCounts.push(quantity);
		});

		if (selectedProductIds.length === 0) {
			layer.msg('请选择要结算的商品', { icon: 2 });
			return;
		}

		const productIdParam = selectedProductIds.join(',');
		const countParam = selectedCounts.join(',');
		const orderUrl = `page/order?productids=${productIdParam}&counts=${countParam}`;
		window.location.href = orderUrl;
	});


	// 为 .lists 列表中的链接添加点击事件
	$('.lists a').on('click', function () {
		const box = $(this).attr('_box');
		window.location.href = `page/profile?box=${box}`;
	});
	// 退出登录逻辑
	const logoutLink = document.getElementById('logoutLink');
	logoutLink.addEventListener('click', function (e) {
		e.preventDefault(); // 阻止默认的链接跳转行为
		// 弹出确认提示框
		if (confirm('确定要退出登录吗？')) {
			$.ajax({
				url: 'logout', // 后端退出登录的接口地址
				method: 'GET',
				success: function (response) {
					if (response.code === 200) {
						// 退出登录成功，给出提示并跳转到登录页面
						alert(response.msg);
						window.location.href = 'page/login';
					} else {
						// 退出登录失败，给出提示
						alert(response.msg);
					}
				},
				error: function (error) {
					console.error('退出登录失败:', error);
					alert('退出登录时发生错误，请稍后再试。');
				}
			});
		}
	});
</script>
</body>

</html>